package it.unipd.dei.es1011.nucularc0d3.defaultproject;

import it.unipd.dei.es1011.nucularc0d3.defaultproject.util.DataWorker;
import it.unipd.dei.es1011.nucularc0d3.defaultproject.util.Details;

import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * This class show the List of previously Recorded Session.
 * It permit to View in details a session by click on it or to delete it by
 * long click on it.
 * @author darkfrank
 *
 */
public class ListSessionsActivity extends Activity {
	
	private LinkedList<Details> sessions;
	private ListView list;
	private EfficientAdapter mEfficientAdapter;
	
//	/**
//	 * Standard override to get key-press events.
//	 * I will delete the connection to the service, the service will stop when it is unbind.
//	 */
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent msg) {
//		if(keyCode == KeyEvent.KEYCODE_BACK){
//			startActivity(new Intent(this, MainActivity.class)); 
//			this.finish();
//			return true;
//		}
//		return super.onKeyDown(keyCode, msg);
//	}
	
	/**
	 * Create the OK/CANCEL dialog to confirm cancellation of the selected records.
	 */
	@Override
	protected Dialog onCreateDialog(final int id) {
		return new AlertDialog.Builder(ListSessionsActivity.this)
		.setIcon(R.drawable.alert_dialog_icon)
		.setTitle(R.string.alert_dialog_two_buttons_title)
		.setMessage(R.string.alert_dialog_msg)
		.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				/* User clicked OK so do some stuff */
				try {
					/** remove data from disk */
					DataWorker.removeSessionFromDisk(sessions.get(id), ListSessionsActivity.this);
					/** remove session from list */
					sessions.remove(id);
					/** force refresh the listview */
					mEfficientAdapter.notifyDataSetChanged();
				} catch (FileNotFoundException e) {
					Log.w("FNF", e.getMessage());
				}
			}
		})
		.setNegativeButton(R.string.alert_dialog_cancel, null).create();
	}
	/** This class realize the List */
	private class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Bitmap mIconX;
		private Bitmap mIconY;
		private Bitmap mIconZ;
		
		private List<Details> mData;

		public EfficientAdapter(Context context, List<Details> sessions) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);

			mData = sessions;
			
			// Icons bound to the rows.
			mIconX = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_x);
			mIconY = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_y);
			mIconZ = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_z);
		}

		/**
		 * The number of items in the list is determined by the number of speeches
		 * in our array.
		 *
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return mData.size();
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficient to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 *
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return position;
		}

		/**
		 * Use the array index as a unique id.
		 *
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 *
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is no need
			// to reinflate it. We only inflate a new View when the convertView supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_records, null);
				// Creates a ViewHolder and store references to the two children views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.icon_x = (ImageView) convertView.findViewById(R.id.icon_axis_x);
				holder.icon_y = (ImageView) convertView.findViewById(R.id.icon_axis_y);
				holder.icon_z = (ImageView) convertView.findViewById(R.id.icon_axis_z);
				holder.text1 = (TextView) convertView.findViewById(R.id.date);
				holder.text2 = (TextView) convertView.findViewById(R.id.time);
				holder.count = (TextView) convertView.findViewById(R.id.count);

				convertView.setTag(holder);
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}

			// Bind the data efficiently with the holder.
			holder.count.setText((position+1) + "/" + mData.size());
			
			Details strings = mData.get(position);
			holder.text1.setText(strings.date);
			holder.text2.setText(strings.time);
			if(strings.x)
				holder.icon_x.setImageBitmap(mIconX);
			else
				holder.icon_x.setImageBitmap(null); // set null or it will appear in the first entry
			if(strings.y)
				holder.icon_y.setImageBitmap(mIconY);
			else
				holder.icon_y.setImageBitmap(null);
			if(strings.z)
				holder.icon_z.setImageBitmap(mIconZ);
			else
				holder.icon_z.setImageBitmap(null);

			return convertView;
		}

		class ViewHolder {
			TextView count;
			TextView text1;
			TextView text2;
			ImageView icon_x;
			ImageView icon_y;
			ImageView icon_z;
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		/** Set the layout of the page, a list whith a header banner */
		setContentView(R.layout.list_h_and_f);
		
		/** create the new data structure and populate it whith data from 
		 * disk. */
		sessions = new LinkedList<Details>();
		DataWorker.loadThumbsFromDisk(sessions, this);
		
		/** instantiate the new EfficientAdapter that generate the list 
		 * to show */
		mEfficientAdapter = new EfficientAdapter(this, sessions);
		/** Instantiate of the ListView bring from id, set the adapter
		 * our mEfficentAdapter and set the action for item click and
		 * item long click */
		list = (ListView) findViewById(R.id.listView);
		list.setAdapter(mEfficientAdapter);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// Start a new Activity that show the list of presents records.
				Intent intent = new Intent(arg1.getContext(), Graphizer.class);
				String fileName = DataWorker.generateFullPathName(sessions.get(position));
				intent.putExtra("fileName", fileName); // the name of xml to load
				startActivity(intent);
			}
		});
		list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				showDialog(position); //ask user what to do.
				return true;
			}
		});
		Toast.makeText(getApplicationContext(), 
			    "Long press to delete a session", 
			    Toast.LENGTH_SHORT).show();
	}
}